package top.lixunda.ecommerce.server.good.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.lixunda.common.utils.ObjectValidators;
import top.lixunda.ecommerce.server.business.BaseServiceImpl;
import top.lixunda.ecommerce.server.business.api.entity.BusinessConstants;
import top.lixunda.ecommerce.server.business.api.entity.cache.CacheUser;
import top.lixunda.ecommerce.server.good.api.entity.db.GoodsDO;
import top.lixunda.ecommerce.server.good.api.entity.db.SubGoodDO;
import top.lixunda.ecommerce.server.good.api.entity.db.UserCarDO;
import top.lixunda.ecommerce.server.good.api.entity.dto.AddUserCarDTO;
import top.lixunda.ecommerce.server.business.api.entity.dto.PageDTO;
import top.lixunda.ecommerce.server.good.api.entity.dto.UserCarQueryDTO;
import top.lixunda.ecommerce.server.good.api.entity.vo.UserCarVO;
import top.lixunda.ecommerce.server.good.mapper.GoodsMapper;
import top.lixunda.ecommerce.server.good.mapper.SubGoodMapper;
import top.lixunda.ecommerce.server.good.mapper.UserCarMapper;
import top.lixunda.ecommerce.server.good.service.IUserCarService;

import java.util.List;

/**
 * <p>
 * 购物车表 服务实现类
 * </p>
 *
 * @author Xumda
 * @since 2019-12-18
 */
@Slf4j
@Service
public class UserCarServiceImpl
        extends BaseServiceImpl<UserCarMapper, UserCarDO>
        implements IUserCarService {

    private final GoodsMapper goodsMapper;

    private final SubGoodMapper subGoodMapper;

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    public UserCarServiceImpl(GoodsMapper goodsMapper, SubGoodMapper subGoodMapper) {
        this.goodsMapper = goodsMapper;
        this.subGoodMapper = subGoodMapper;
    }

    /**
     * 添加购物车
     *
     * @param addUserCarDTO 商品数据，包括商品id和商品数量
     * @return 是否添加成功
     */
    @Override
    public Boolean addToCar(AddUserCarDTO addUserCarDTO) {
        UserCarDO userCarDO = new UserCarDO();
        CacheUser userInfoDO = currentUserCacheNotNull();

        SubGoodDO subGoodDO = subGoodMapper.selectById(addUserCarDTO.getGoodId());
        if (ObjectValidators.isEmpty(subGoodDO)) {
            throw getAppException("商品不存在");
        }
        GoodsDO goodsDO = goodsMapper.selectById(subGoodDO.getGoodId());
        if (ObjectValidators.isEmpty(goodsDO)) {
            throw getAppException("商品不存在");
        }
        userCarDO.setUserId(userInfoDO.getAccount());
        userCarDO.setCount(addUserCarDTO.getCount());
        userCarDO.setGoodId(goodsDO.getId());
        userCarDO.setGoodName(goodsDO.getName());
        userCarDO.setSubGoodId(subGoodDO.getId());
        userCarDO.setSubGoodName(subGoodDO.getSubGoodName());
        userCarDO.setStoreId(goodsDO.getStoreId());
        userCarDO.setStoreName(goodsDO.getStoreName());
        userCarDO.setPrice(subGoodDO.getPrice());
        userCarDO.setUseableDesc("添加购物车");
        boolean success = this.save(userCarDO);
        if (!success) {
            log.debug("添加购物车失败：{}", userCarDO.toString());
            throw getAppException("添加购物车失败");
        }
        return true;
    }

    /**
     * 移除购物车
     *
     * @param ids 商品在购物车中的id列表
     * @return 移除数量
     */
    @Override
    public Integer removeCar(List<Integer> ids) {
        CacheUser userInfoDO = currentUserCacheNotNull();
        // 通过更改useable参数的方式移除数据
        boolean success = this.update(new LambdaUpdateWrapper<UserCarDO>()
                .in(UserCarDO::getId, ids)
                .eq(UserCarDO::getUserId, userInfoDO.getAccount())
                .eq(UserCarDO::getUseable, BusinessConstants.USEABLE_TRUE)
                .set(UserCarDO::getUseableDesc, "移除购物车")
                .set(UserCarDO::getUseable, BusinessConstants.USEABLE_FALSE));
        if (!success) {
            throw getAppException("移除购物车失败");
        }
        return ids.size();
    }

    /**
     * 分页条件查询购物车
     *
     * @param pageDTO 分页数据及条件查询数据
     * @return 购物车分页数据
     */
    @Override
    public IPage<UserCarVO> queryCarGoodsByPage(PageDTO<UserCarDO, UserCarQueryDTO> pageDTO) {
        CacheUser userInfoDO = currentUserCacheNotNull();
        IPage<UserCarDO> page = this.page(
                pageDTO.getPage(),
                pageDTO.getWrapper(
                        wrapper -> wrapper.eq(UserCarDO::getUserId, userInfoDO.getAccount())));
        return pageConvert(page, UserCarVO::fromUserCarDO);
    }

}
